/*
 * @Author: LF
 * @Description: 个人中心页
 * @Date: 2020-10-21 08:38:38
 * @LastEditTime: 2020-10-23 09:22:28
 */
import React, { Component } from 'react'
// 引入上传图片，ICON图标，提醒框，确认框组件
import { Upload, Icon, message, Modal, Form, Input } from 'antd'
// 引入上传图片的地址
import { uploadAvatarURL } from '../config'
import jwt from 'jsonwebtoken'
import { updateAvatar, updatePassword } from '@/services/user'

class personalCenter extends Component {
  constructor(props) {
    super(props)

    this.state = {
      loading: false,
      imageUrl: '',
      visible: false
    }
  }

  // 上传图片的函数
  uploadChange = async (file) => {
    // 上传中
    if (file.file.status === 'uploading') {
      return this.setState({ loading: true })
    }
    // 上传完成
    if (file.file.status === 'done') {
      // 发起修改头像请求，将图片地址存储到用户信息中
      let { data: res } = await updateAvatar({
        avatar: file.file.response.path
      })
      if (res && res.ok !== 1) {
        return message.error(res.msg)
      }
      message.success('头像修改成功!')
      this.setState({ loading: false })
      setTimeout(() => {
        window.location.reload()
      }, 1000)
    }
  }

  // 修改密码
  handleOk = () => {
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        let { data: res } = await updatePassword(values)
        if (res && res.ok !== 1) {
          return message.error(res.msg)
        }
        this.operationModal(false)
        message.success(res.msg)
      }
    })
  }

  comfirmPasswordCheck = (rules, value, callback) => {
    if (value !== this.props.form.getFieldsValue(['password']).password) {
      callback('两次输入的密码不一致!')
    } else if (
      value === this.props.form.getFieldsValue(['oldPassword']).oldPassword
    ) {
      callback('新密码不能与原密码相同!')
    }
    callback()
  }

  operationModal = (value) => {
    if (!value) {
      this.props.form.resetFields()
    }
    this.setState({
      visible: value
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form
    const uploadButton = (
      <>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </>
    )
    const formItemLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 20 }
      }
    }
    return (
      <div>
        <div className="center-nav">
          <div className="center-nav-left">
            <div className="account-msg-head">
              <h2>个人中心</h2>
            </div>
            <div className="account-msg-body">
              <div className="user-avatar-box">
                <div>更改头像:</div>
                <Upload
                  className="upload-avatar"
                  listType="picture-card"
                  showUploadList={false}
                  action={uploadAvatarURL}
                  onChange={this.uploadChange}
                  headers={{ token: sessionStorage.getItem('token') }}
                >
                  {this.state.imageUrl ? (
                    <img
                      src={this.state.imageUrl}
                      alt="avatar"
                      style={{ width: '100%' }}
                    />
                  ) : (
                    uploadButton
                  )}
                </Upload>
              </div>
              <div className="user-avatar-box">
                <div>用户名:</div>
                <div style={{ marginLeft: '1rem' }}>
                  {jwt.decode(sessionStorage.getItem('token')).username}
                </div>
              </div>
              <div className="user-avatar-box">
                <div>密码:</div>
                <button
                  className="btn"
                  onClick={() => this.operationModal(true)}
                >
                  修改密码
                </button>
              </div>
            </div>
          </div>
          <div className="center-nav-right"></div>
        </div>
        <Modal
          title="修改密码"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={() => this.operationModal(false)}
          okText="确认"
          cancelText="取消"
        >
          <Form {...formItemLayout}>
            <Form.Item label="原密码">
              {getFieldDecorator('oldPassword', {
                rules: [
                  {
                    required: true,
                    message: '原密码不能为空!'
                  }
                ]
              })(<Input.Password placeholder="请输入原密码" />)}
            </Form.Item>
            <Form.Item label="新密码">
              {getFieldDecorator('password', {
                rules: [
                  {
                    required: true,
                    message: '新密码不能为空!'
                  },
                  {
                    min: 6,
                    max: 18,
                    message: '新密码必须在6到18位之间'
                  }
                ]
              })(<Input.Password placeholder="请输入新密码" />)}
            </Form.Item>
            <Form.Item label="确认密码">
              {getFieldDecorator('comfirmPassword', {
                rules: [
                  {
                    required: true,
                    message: '确认密码不能为空!'
                  },
                  { validator: this.comfirmPasswordCheck }
                ]
              })(<Input.Password placeholder="请再次输入新密码" />)}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}

const personalCenterForm = Form.create()(personalCenter)
export default personalCenterForm
